﻿using HANS.Utility.Extensions;
using HANS_BackStage.Common;
using HANS_BackStage.Model.WebModel;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HANS_BackStageWeb.Common
{
    [BackStagAuthorize]
    public class CommonController : BaseController
    {
        // GET: Common
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            #region 加载默认配置
            ViewBag.DefaultFaceImagePath = @"~/content/Image/login/head.png";//默认头像
            #endregion

            if (!(new string[] { })
             .Contains(filterContext.RequestContext.RouteData.Values["controller"].ToString().ToLower())
            && filterContext.Result.GetType() == typeof(ViewResult))
            {
                ViewBag.Login_AdminInfo = AdminSession;
            }
        }

        public Login_AdminInfo AdminSession
        {
            get
            {
                return Session[SessionConstant.ADMININFO_KEY] as Login_AdminInfo;
            }
            set
            {
                Session[SessionConstant.ADMININFO_KEY] = value;
            }
        }
        /// <summary>
        /// 管理员登录
        /// </summary>
        protected void Admin_SignIn(Login_AdminInfo adminSession, bool rememberMe)
        {
            FormsAuthenticationHelper.SignIn(adminSession.Name, rememberMe);
            AdminSession = adminSession;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        protected void Admin_SignOut()
        {
            FormsAuthenticationHelper.SignOut();
            Session.Abandon();
        }

        /// <summary>
        /// 利用查询字符串构造分页视图需要的ViewData
        /// </summary>
        protected virtual ViewDataDictionary GetParameterFromQueryString()
        {
            ViewDataDictionary result = new ViewDataDictionary();
            foreach (var key in Request.QueryString.AllKeys)
            {
                if (!key.EqualsNoCase("page") && Request[key].IsNotNullAndNotWhiteSpace())
                {
                    result.Add(key, Request[key]);
                }
            }
            return result;
        }

        #region 方法

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        protected virtual string SaveFile(HttpPostedFileBase file, string path)
        {
            bool hasImg = file.IsNotNull() && file.ContentLength > 0 && file.FileName.IsNotNullAndNotWhiteSpace();
            var fileName = ""; //要保存的文件名
            if (hasImg)
            {
                fileName = Guid.NewGuid().ToString().GetMD5Hash() + Path.GetExtension(file.FileName);
                var userPath = HttpContext.Server.MapPath(path);
                if (!Directory.Exists(userPath))
                {
                    Directory.CreateDirectory(userPath);
                }
                var physicalPath = Path.Combine(userPath, Path.GetFileName(fileName));
                file.SaveAs(physicalPath); //保存图片
                return GetFileRelativePath(fileName, path);
            }
            return null;
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        protected virtual string SaveFile(string fieldName, string path)
        {
            HttpPostedFileBase file = Request.Files[fieldName];
            return SaveFile(file, path);
        }

        
        protected virtual void SaveFiles(string basePath, Action<string> filePathHandler = null, int maxFileCount = 9)
        {
            var fileCount = maxFileCount < Request.Files.Count ? maxFileCount : Request.Files.Count;
            for (int i = 0; i < fileCount; i++)
            {
                var file = Request.Files[i];
                if (file.ContentLength == 0) continue;
                var relativePath = SaveFile(file, basePath);
                if (relativePath.IsNotNullAndNotWhiteSpace()) filePathHandler(relativePath);
            }
        }
        #endregion
    }
}